package com.qunar.crawler.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HtmlPossesserBread {
	private static final Logger logger = LoggerFactory
			.getLogger(HtmlPossesserBread.class);
	private static Pattern date = Pattern.compile("\\d{4}_\\d{2}_\\d{2}");
	private static String TABLE_NAME = "bread";

	public static Object digBeforeDate(String html) {

		try {
			NodeFilter filter = new NodeClassFilter(Div.class);

			Parser parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("utf-8");

			NodeList list = parser.extractAllNodesThatMatch(filter);

			for (int i = 0; i < list.size(); i++) {

				Div node = (Div) list.elementAt(i);
				if ("before".equalsIgnoreCase(node.getAttribute("class"))) {
					// System.out.println(node.toHtml());

					return StringUtils
							.isBlank(node.getAttribute("data-before")) ? null
							: node.getAttribute("data-before").trim();
				}

			}

		} catch (ParserException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String digFirstBeforeDate(String html) {

		try {
			NodeFilter filter = new NodeClassFilter(Div.class);

			Parser parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("utf-8");

			NodeList list = parser.extractAllNodesThatMatch(filter);

			for (int i = 0; i < list.size(); i++) {

				Div node = (Div) list.elementAt(i);
				if ("live-contents"
						.equalsIgnoreCase(node.getAttribute("class"))) {
					// System.out.println(node.toHtml());

					return StringUtils
							.isBlank(node.getAttribute("data-before")) ? null
							: node.getAttribute("data-before").trim();
				}

			}

		} catch (ParserException e) {
			e.printStackTrace();
		}

		return null;

	}

	/** --------返回插入的图片数----------- */
	public static int addPic2DB(List<Bread> list) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int affectRowCount = 0;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "INSERT IGNORE INTO " + TABLE_NAME
					+ " (url,DATE,author) VALUES(?,?,?) ";
			pstmt = conn.prepareStatement(sql);

			long begin = System.currentTimeMillis();
			for (Bread b : list) {
				pstmt.setString(1, b.getImgUrl());
				pstmt.setString(2, b.getDate());
				pstmt.setString(3, b.getUsername());
				pstmt.addBatch();
			}

			int[] result = pstmt.executeBatch();

			long end = System.currentTimeMillis();
			affectRowCount = 0;
			for (int i : result) {
				affectRowCount += i;
			}
			logger.info("追加图片到数据库耗时:"
					+ (end - begin)
					+ "ms.\n本次增加"
					+ affectRowCount
					+ "张新图片！"
					+ "时间："
					+ new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss")
							.format(new Date()));
			logger.info("时间："
					+ new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss")
							.format(new Date()));
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			JdbcUtils.release(conn, pstmt, rs);
		}

		return affectRowCount;
	}

	/** ---------从url中截取出日期-------------- */
	public static String getDate(String url) {
		Matcher m = date.matcher(url);
		while (m.find()) {
			return m.group();
		}
		return "";
	}

	// 查找所有class=feed-content float-left的div,并从中找出所有用户名称和发的图片URL
	// 新面包旅行解析代码
	public static void digSubNodes(String html, List<Bread> breads) {

		try {
			NodeFilter filter = new NodeClassFilter(Div.class);

			Parser parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("utf-8");

			NodeList list = parser.extractAllNodesThatMatch(filter);

			for (int i = 0; i < list.size(); i++) {

				Div node = (Div) list.elementAt(i);
				if ("live-item pr".equalsIgnoreCase(node.getAttribute("class"))) {
					Bread b = new Bread();
					// System.out.println(node.toHtml());
					digPic(node.toHtml(), b);
					if (b.getImgUrl() == null)
						continue;
					digUser(node.toHtml(), b);
					b.setDate(getDate(b.getImgUrl()));
					System.out.println(b);
					breads.add(b);

				}

			}

		} catch (ParserException e) {
			e.printStackTrace();
		}

	}

	// 挖掘用户
	public static void digUser(String html, Bread bread) {

		try {
			NodeFilter filter = new NodeClassFilter(Div.class);

			Parser parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("utf-8");

			NodeList list = parser.extractAllNodesThatMatch(filter);

			for (int i = 0; i < list.size(); i++) {

				// LinkTag link = (LinkTag) list.elementAt(i);
				Div div = (Div) list.elementAt(i);
				if ("name".trim().equalsIgnoreCase(div.getAttribute("class"))) {

					LinkTag link = (LinkTag) div.getChild(1);
					// System.out.println("用户名：" + link.getLinkText());
					bread.setUsername(link.getLinkText());
				}
			}

		} catch (ParserException e) {
			e.printStackTrace();
		}
	}

	// 挖掘图片
	public static void digPic(String html, Bread bread) {

		try {
			NodeFilter filter = new NodeClassFilter(ImageTag.class);

			Parser parser = new Parser();
			parser.setInputHTML(html);
			parser.setEncoding("utf-8");

			NodeList list = parser.extractAllNodesThatMatch(filter);

			for (int i = 0; i < list.size(); i++) {

				// Div div = (Div) list.elementAt(i);
				ImageTag img = (ImageTag) list.elementAt(i);
				if ("hidden".trim().equalsIgnoreCase(img.getAttribute("class"))) {

					// System.out.println(div.getAttribute("style"));
					// System.out.println("图片Url:" + img.getImageURL());
					bread.setImgUrl(img.getImageURL());
				}
			}

		} catch (ParserException e) {
			e.printStackTrace();
		}
	}

	// private static void digTrip(String html, Bread bread) {
	// try {
	// NodeFilter filter = new NodeClassFilter(Span.class);
	//
	// Parser parser = new Parser();
	// parser.setInputHTML(html);
	// parser.setEncoding("utf-8");
	//
	// NodeList list = parser.extractAllNodesThatMatch(filter);
	//
	// for (int i = 0; i < list.size(); i++) {
	//
	// Span span = (Span) list.elementAt(i);
	// if ("ellipsis_text".trim().equalsIgnoreCase(
	// span.getAttribute("class"))) {
	//
	// // System.out.println(div.getAttribute("style"));
	// System.out.println("游记名:" + span.getStringText());
	// bread.setTrip(span.getStringText());
	// }
	// }
	//
	// } catch (ParserException e) {
	// e.printStackTrace();
	// }
	// }
	public static void main(String[] args) {
		System.out.println(getDate("http://breadtripimages.qiniudn.com/photo_2013_08_15_902d0b75600a5bc0ff8bea5d9b3f7d80.jpg?imageView/2/w/278/q/75"));
	}

}
